/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
 * <p>Project: jdemo202203 - Demo1
 * <p>Powered by webrx On 2022-10-31 19:45:45
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Demo1 {
    Connection conn;

    @BeforeEach
        //@Test
    void init() throws IOException {
        //加载src/main/resources/db.properties文件配置  信息
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
        Properties prop = new Properties();
        prop.load(is);
        String driver = prop.getProperty("db.driver", "com.mysql.cj.jdbc.Driver");
        String url = prop.getProperty("db.url", "jdbc:mysql:/");
        String user = prop.getProperty("db.username", "root");
        String pwd = prop.getProperty("db.password", "");
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Test
    void conn(){
        try {
            String url="jdbc:mysql://localhost:3306/dbshop";
            String user="root";
            String password="";
            Connection conn= DriverManager.getConnection(url,user,password);
            System.out.println(conn);
            System.out.println(conn.getMetaData().getDatabaseProductVersion());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    @DisplayName("Statement")
    void m1(){
        // System.out.println(conn);
        try{
            Statement stmt=conn.createStatement();
            //execute() 方法用来执行ddl语句
            stmt.execute("create database if not exists dbaa");
            //executeQuery()方法用来执行select show等查询语句，有查询结果
            ResultSet rs=stmt.executeQuery("show databases");
            while(rs.next()){
                System.out.println(rs.getString(1));
            }
            //插入数据 .executeUpdate()方法 可以执行insert delete uodate
            //stmt.executeUpdate("")
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @AfterEach
    void close(){
        try {
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
